package com.wei.czz.framework.common.helper;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wei.czz.common.constant.RedisConstant;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.utils.GuavaUtils;
import com.wei.czz.framework.common.handler.ThrottleHandler;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2024-04-27 13:41:04
 * className: CacheHelper 缓存帮助类
 * version: 1.0
 * description:
 */
@Component
@AllArgsConstructor
public class CacheHelper {

    private static final Logger log = LoggerFactory.getLogger(CacheHelper.class);

    private final RedisTemplate<String, Object> redisTemplate;

    private final RedissonClient redissonClient;

    private final ThrottleHandler throttleHandler;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public void cache(String key, Object value) {
        String cacheValue;
        if (value instanceof String) {
            cacheValue = (String) value;
        } else {
            cacheValue = this.toJsonString(value);
        }

        // 本地缓存
        GuavaUtils.set(key, cacheValue);
        // redis缓存，缓存时长和本地缓存一致
        redisTemplate.opsForValue().set(key, cacheValue, GuavaUtils.CACHE_MILLIS, TimeUnit.MILLISECONDS);
    }

    public void cache(String key, Object value, long timeout, TimeUnit unit) {
        String cacheValue;
        if (value instanceof String) {
            cacheValue = (String) value;
        } else {
            cacheValue = this.toJsonString(value);
        }

        if (unit.toMillis(timeout) >= GuavaUtils.CACHE_MILLIS) {
            // 如果缓存时长大于等于本地缓存时长，则添加本地缓存
            GuavaUtils.set(key, cacheValue);
        }

        // redis缓存
        redisTemplate.opsForValue().set(key, cacheValue, timeout, unit);
    }

    public String get(String key) {
        // 从本地缓存中获取
        String cacheValue = GuavaUtils.get(key);
        if (StringUtils.isNotBlank(cacheValue)) {
            log.info("从本地缓存中获取到数据。key={} cacheValue={}", key, cacheValue);
            return cacheValue;
        }
        // 从redis中获取
        cacheValue = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(cacheValue)) {
            log.info("从redis中获取到数据。key={} cacheValue={}", key, cacheValue);
            // 尝试设置本地缓存
            this.tryLocalCache(key, cacheValue);
        }
        return cacheValue;
    }

    public <T> T get(String key, Class<T> clazz) {
        String cacheValue = this.get(key);
        if (StringUtils.isBlank(cacheValue)) {
            return null;
        }
        return this.parseJson(cacheValue, clazz);
    }

    public <T> T get(String key, TypeReference<T> typeReference) {
        String cacheValue = this.get(key);
        if (StringUtils.isBlank(cacheValue)) {
            return null;
        }
        return this.parseJson(cacheValue, typeReference);
    }


    public <T> T get(String key, Class<T> clazz, Supplier<T> supplier) {
        String cacheValue = GuavaUtils.get(key);
        if (StringUtils.isNotBlank(cacheValue)) {
            log.info("从本地缓存中获取到数据");
            return this.parseJson(cacheValue, clazz);
        }
        cacheValue = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(cacheValue)) {
            log.info("从redis中获取到数据");
            // 尝试设置本地缓存
            this.tryLocalCache(key, cacheValue);

            return this.parseJson(cacheValue, clazz);
        }
        RLock lock = redissonClient.getLock(RedisConstant.LOCK + key);
        lock.lock();
        try {
            // double check
            cacheValue = GuavaUtils.get(key);
            if (StringUtils.isNotBlank(cacheValue)) {
                log.info("double check-从本地缓存中获取到数据");
                return this.parseJson(cacheValue, clazz);
            }
            cacheValue = (String) redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(cacheValue)) {
                log.info("double check-从redis中获取到数据");
                // 尝试设置本地缓存
                this.tryLocalCache(key, cacheValue);

                return this.parseJson(cacheValue, clazz);
            }

            // 获取数据逻辑
            T t = supplier.get();

            // 序列化
            cacheValue = this.toJsonString(t);

            // 设置本地缓存
            GuavaUtils.set(key, cacheValue);

            // redis缓存，缓存时长和本地缓存一致
            redisTemplate.opsForValue().set(key, cacheValue, GuavaUtils.CACHE_MILLIS, TimeUnit.MILLISECONDS);

            return t;
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public void delete(String key) {
        // 删除本地缓存
        GuavaUtils.remove(key);
        // 删除redis缓存
        redisTemplate.delete(key);
    }

    public void delete(List<String> keyList) {
        for (String key : keyList) {
            // 删除本地缓存
            GuavaUtils.remove(key);
        }
        // 删除redis缓存
        redisTemplate.delete(keyList);
    }

    /**
     * json字符串反序列化
     * @param value 值
     * @param clazz 类型
     * @return 类型对象
     * @param <T> 泛型
     */
    private <T> T parseJson(String value, Class<T> clazz) {
        try {
            return objectMapper.readValue(value, clazz);
        } catch (JsonProcessingException e) {
            log.error("字符串反序列化异常。value={} message={}", value, e.getMessage(), e);
            throw new CzzException();
        }
    }

    /**
     * json字符串反序列化
     * @param value         值
     * @param typeReference 自定义类型转换方式
     * @return 类型对象
     * @param <T> 泛型
     */
    private <T> T parseJson(String value, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(value, typeReference);
        } catch (JsonProcessingException e) {
            log.error("字符串反序列化异常。message={}", e.getMessage(), e);
            throw new CzzException();
        }
    }

    /**
     * 对象序列化
     * @param object 参数对象
     * @return json格式字符串
     */
    private String toJsonString(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("对象序列化异常。message={}", e.getMessage(), e);
            throw new CzzException();
        }
    }

    /**
     * 尝试设置本地缓存
     * @param key   缓存键
     * @param value 缓存值
     */
    private void tryLocalCache(String key, String value) {
        throttleHandler.throttleRun(() -> {
            // 获取redis缓存过期时间
            Long expire = redisTemplate.getExpire(key, TimeUnit.MILLISECONDS);
            if (Objects.equals(expire, -1L) || expire > GuavaUtils.CACHE_MILLIS) {
                /*
                    1、redis缓存不会过期
                    2、redis缓存过期时长大于本地缓存时长
                    新增本地缓存
                 */
                GuavaUtils.set(key, value);
            }
        }, key, 10, TimeUnit.SECONDS);
    }

}
